package com.licheedev.silentinstall

import android.content.Context
import android.content.Intent
import com.chrisplus.rootmanager.RootManager
import java.io.File


object SilentInstall {

    internal var packageReplacedAction: ((intent: Intent) -> Unit)? = null

    /**
     * 初始化
     * @param packageReplacedAction Function0<Unit> 安装完成后的回调
     */
    fun setup(packageReplacedAction: (intent: Intent) -> Unit) {
        this.packageReplacedAction = packageReplacedAction
    }

    /**
     * 安装apk
     * @param apkInfo ApkInfo apk信息
     */
    fun install(apkInfo: ApkInfo) {
        RootManager.getInstance().installPackage(apkInfo.path)
    }

    /**
     * 安装apk
     * @param apkFile File apk文件
     */
    fun install(apkFile: File) {
        RootManager.getInstance().installPackage(apkFile.absolutePath)
    }

    /**
     * 安装apk
     * @param apkPath String apk文件路径
     */
    fun install(apkPath: String) {
        RootManager.getInstance().installPackage(apkPath)
    }

    /**
     * 创建启动应用使用的Intent，防止点击launcher的图标后重复启动
     * @param context Context
     * @param clazz Class<T>
     * @return Intent
     */
    fun <T> launchIntent(context: Context, clazz: Class<T>): Intent {
        val intent = Intent(context, clazz)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
        intent.action = Intent.ACTION_MAIN
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        return intent
    }
}